//
//  WeChooseDetailViewController.m
//  代号：47
//
//  Created by lanou3g on 15/7/2.
//  Copyright (c) 2015年 杨佩璋. All rights reserved.
//

#import "WeChooseDetailViewController.h"
#import "WeChooseDetailView.h"
#import "RequestManager.h"
#import "NSString+Html.h"
#import "ChooseDetailModel.h"
#import "UMSocial.h"
#import <UIImageView+WebCache.h>

#import "TFHpple.h"
//#import "TFHppleElement.h"
//#import "XPathQuery.h"


#define kUrl @"http://api2.pianke.me/article/info"


@interface WeChooseDetailViewController ()<RequestDelegate,UIWebViewDelegate,UMSocialUIDelegate,UIScrollViewDelegate>{
    
    UIView *bgView;//灰色背景图片
    UIImageView *imgView;//scrollView上面的图片
    NSInteger _numOfImageInWebView;//图片的数量
}

@property (nonatomic ,retain)ChooseDetailModel *detailModel;//数据模型
@property (nonatomic ,retain)WeChooseDetailView *detailV;//加上View
@property (nonatomic ,retain)UIWebView *webView;//一个webView
@property (nonatomic ,retain)UIScrollView *imageScrollView;//创建一个scrollView来显示图片

@property (nonatomic ,retain)NSMutableArray *webViewUrls;//存储web里面所有图片的数组

@end

@implementation WeChooseDetailViewController

- (void)dealloc
{
    [_detailV release];
    [_detailModel release];
    [_webView release];
    [_chooseModel release];
    [super dealloc];
}
-(void)loadView{
    self.detailV = [[WeChooseDetailView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = _detailV;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftItemsSupplementBackButton = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.leftBarButtonItem = nil;
    self.webViewUrls = [NSMutableArray arrayWithCapacity:0];
    
    UIBarButtonItem *barBtnItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(handleShareAction:)];
    self.navigationItem.rightBarButtonItem = barBtnItem;
    
    //初始化imageScrollView
    self.imageScrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _imageScrollView.backgroundColor = [UIColor blackColor];
    
    
    [self requestData];
    
//    _detailV.mainTableView.delegate = self;
//    _detailV.mainTableView.dataSource = self;
//    _detailV.mainTableView.rowHeight = 200;
}

- (void)handleShareAction:(UIBarButtonItem *)barItem{

    
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_chooseModel.coverimg]];
    //注意：分享到微信好友、微信朋友圈、微信收藏、QQ空间、QQ好友、来往好友、来往朋友圈、易信好友、易信朋友圈、Facebook、Twitter、Instagram等平台需要参考各自的集成方法
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5596467567e58e628d004df4"
                                      shareText:[NSString stringWithFormat:@"%@  %@ \n",_chooseModel.title,_detailModel.url]
                                     shareImage:[UIImage imageWithData:data]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToDouban,nil]
                                       delegate:self];
    
}

#pragma mark----------tableView协议实现 -----------------已经删除
//-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    return 0;
//}
//-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    DetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
//    
//    cell.detailModel = _detailModel;
//    
//    [cell.allArticalBtn addTarget:self action:@selector(handleAllArticalButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
//    return cell;
//}
//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    
//    DetailTableViewCell *ce = [[DetailTableViewCell alloc] init];
//    
//    return [ce heightForCell:_detailModel];
//    
//}


- (void)handleAllArticalButtonAction:(UIButton *)button{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark----------数据请求
-(void)requestData{
    
    RequestManager *request  = [[RequestManager alloc] initWithRequestURL:kUrl requestModel:POST parameter:nil];
    NSDictionary *dict  = @{@"auth":@"DcBnEH648f5DCMd9EMzqkTJxQ8qvYb6Oom1puDTw3cWP23txJShxd7f4",@"client":@"1",@"contentid":_chooseModel.ID,@"deviceid":@"0898EF65-3414-425C-B70A-D86B2D4ABAF0",@"version":@"3.0.3"};
    request.parameterDic = [dict mutableCopy];
    
    request.delegate = self;
    [request startRequest];
}
//请求完毕之后让代理对象执行的方法，同时把请求完整的data传给代理对象
- (void)requestDidFinishWithData:(NSData *)data{
    NSDictionary *mainDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves  error:nil];
    self.detailModel = [[ChooseDetailModel alloc] init];
    NSDictionary *dataDict = mainDict[@"data"];
    [_detailModel setValuesForKeysWithDictionary:dataDict];    
    [self loadWebView];
    
    
}
//请求失败后把错误原因传值给代理对象
- (void)requestError:(NSError *)error{
    
    
}


#pragma mark ------------加载webView
- (void)loadWebView{
    
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 300)];
    
    NSString *str = [NSString importStyleWithHtmlString:_detailModel.html];
    [_webView loadHTMLString:str baseURL:[NSURL fileURLWithPath:[NSBundle mainBundle].bundlePath]];
    _webView.delegate = self;
    
    
    NSData *htmlData = [_detailModel.html dataUsingEncoding:NSUTF8StringEncoding];
    NSString *nodeString = @"//img";
    TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
    NSArray *element = [xpathParser searchWithXPathQuery:nodeString];
    for (TFHppleElement *obj in element) {
        NSArray *arr = (obj->node)[@"nodeAttributeArray"];
        NSString *urlStr = [arr firstObject][@"nodeContent"];
        [_webViewUrls addObject:urlStr];
    }
}
//webView协议
- (void)webViewDidFinishLoad:(UIWebView *)webView{

    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    _webView.frame = CGRectMake(kLeftPadding, 0, kScreen_width - 2 * kLeftPadding, height);
    _webView.scrollView.bounces = NO;
    _detailV.mainTableView.tableHeaderView = _webView;

    //调整字号
    NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'";
    [webView stringByEvaluatingJavaScriptFromString:str];
    
    //js方法遍历图片添加点击事件 返回图片个数
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    for(var i=0;i<objs.length;i++){\
    objs[i].onclick=function(){\
    document.location=\"myweb:imageClick:\"+this.src;\
    };\
    };\
    return objs.length;\
    };";

    [webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法
    
//    注入自定义的js方法后别忘了调用 否则不会生效（不调用也一样生效了，，，不明白）
    NSString *resurlt = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
    _numOfImageInWebView = [resurlt integerValue];
//    调用js方法
//    NSLog(@"---调用js方法--%@  %s  jsMehtods_result = %ld",self.class,__func__,_numOfImageInWebView);

}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//    NSLog(@" %d ... %s ... %@",__LINE__,__FUNCTION__,@"00000");
    //将url转换为string
    NSString *requestString = [[request URL] absoluteString];
    
    //hasPrefix 判断创建的字符串内容是否以pic:字符开始
    if ([requestString hasPrefix:@"myweb:imageClick:"]) {
        NSString *imageUrl = [requestString substringFromIndex:@"myweb:imageClick:".length];
//        NSLog(@"image url------%@", imageUrl);
        if (bgView) {
            //设置不隐藏，还原放大缩小，显示图片
            bgView.hidden = NO;

            NSInteger num = _numOfImageInWebView;
            for (int i = 0; i < num; i++) {
                if ([imageUrl isEqualToString:_webViewUrls[i]]) {
                    _imageScrollView.contentOffset = CGPointMake(i * kScreen_width, 0);
                }
            }
        }
        else
            [self showBigImage:imageUrl];//创建视图并显示图片
        
        return NO;
    }
    return YES;
    
    
}

#pragma mark 显示大图片
-(void)showBigImage:(NSString *)imageUrl{
    //创建灰色透明背景，使其背后内容不可操作
    bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, kScreen_height)];
    [bgView setBackgroundColor:[UIColor colorWithRed:0.3
                                               green:0.3
                                                blue:0.3
                                               alpha:0.7]];
    [self.view addSubview:bgView];
    bgView.userInteractionEnabled = YES;
    //创建scrollView
    NSInteger num = _numOfImageInWebView;
    self.imageScrollView  = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, kScreen_width, kScreen_height - 64)];
    _imageScrollView.contentSize = CGSizeMake(kScreen_width * num, kScreen_height - 64);
    _imageScrollView.pagingEnabled = YES;
    _imageScrollView.bounces = NO;
    _imageScrollView.showsHorizontalScrollIndicator = NO;
    
    _imageScrollView.delegate = self;
    _imageScrollView.minimumZoomScale = 1.0;
    _imageScrollView.maximumZoomScale = 3.0;
    [_imageScrollView setZoomScale:1.0];
    [bgView addSubview:_imageScrollView];
    for (int i = 0; i < num; i++) {
        //添加双击手势
//        UITapGestureRecognizer *doubleTap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
//        [doubleTap setNumberOfTapsRequired:2];
        //判断点击的是第几张图片
        if ([imageUrl isEqualToString:_webViewUrls[i]]) {
            _imageScrollView.contentOffset = CGPointMake(i * kScreen_width, 0);
        }
        UIImage *aImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_webViewUrls[i]]]];
        CGFloat height = (aImage.size.height) * kScreen_width / aImage.size.width;
        imgView = [[UIImageView alloc] initWithFrame:CGRectMake(kScreen_width * i, 0, kScreen_width, height)];
//        [imgView addGestureRecognizer:doubleTap];
        [imgView sd_setImageWithURL:[NSURL URLWithString:_webViewUrls[i]]];
        imgView.center = CGPointMake(kScreen_width / 2 + i * kScreen_width, (kScreen_height - 64) / 2);
        [_imageScrollView addSubview:imgView];
        [imgView release];
        
        
        UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake((kScreen_width / 2 - 30) + i * kScreen_width, kScreen_height - 40 - 64, 60, 30)];
        aLabel.textAlignment = NSTextAlignmentCenter;
        aLabel.text = [NSString stringWithFormat:@"%d/%ld",i + 1,(long)num];
        aLabel.textColor = [UIColor whiteColor];
        [_imageScrollView addSubview:aLabel];
        [aLabel release];
    }

    
    
    //创建关闭按钮
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [closeBtn setImage:[UIImage imageNamed:@"close.png"] forState:UIControlStateNormal];
    //    closeBtn.backgroundColor = [UIColor redColor];
    [closeBtn setTintColor:[UIColor cyanColor]];
    [closeBtn setImage:[UIImage imageNamed:@"iconfont-guanbi"] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(removeBigImage) forControlEvents:UIControlEventTouchUpInside];
    [closeBtn setFrame:CGRectMake(kScreen_width - 40, 64, 30, 30)];
    [bgView addSubview:closeBtn];
    
    
}
//关闭按钮
-(void)removeBigImage
{
    bgView.hidden = YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
